from django import forms
from django.contrib.auth import forms as auth_forms
from django.forms.models import inlineformset_factory
from django.utils.translation import ugettext as _

from crispy_forms.helper import FormHelper

from course.models import Course
from resume.models import Resume
from .models import (
    User,
    StudyExperience, WorkExperience,
)
from .contants import (
    GROUP_STUDENT, GROUP_TEACHER,
    GROUP_SUPERVISOR, GROUP_ASSISTANT
)


class UserForm(forms.ModelForm):

    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
    }
    password1 = forms.CharField(
        label=_("Password"),
        widget=forms.PasswordInput,
        required=False,
    )
    password2 = forms.CharField(
        label=_("Password confirmation"),
        widget=forms.PasswordInput,
        required=False,
        help_text=_("Enter the same password as above, for verification.")
    )

    class Meta:
        model = User
        fields = ("email", "first_name", "last_name", "is_active",
                  "groups", "username", "wechat", "linkedin", "weibo",
                  "facebook", "twitter", "mobile", "docs_url", "bio",
                  "teaching", "enrolling")

    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        self.fields['username'].required = False

        if 'instance' not in kwargs or not kwargs['instance']:
            self.fields['teaching'].queryset = Course.objects.valid_courses()
            self.fields['enrolling'].queryset = Course.objects.valid_courses()
            return

        if kwargs['instance'].is_in_group(GROUP_SUPERVISOR):
            del self.fields['enrolling']
            del self.fields['docs_url']
        elif kwargs['instance'].is_in_group(GROUP_TEACHER):
            del self.fields['enrolling']
            del self.fields['docs_url']
        elif kwargs['instance'].is_in_group(GROUP_STUDENT):
            del self.fields['teaching']
            del self.fields['username']
        elif kwargs['instance'].is_in_group(GROUP_ASSISTANT):
            del self.fields['enrolling']
            del self.fields['teaching']
            del self.fields['docs_url']

        # print(self.fields)

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

    def save(self, commit=True):
        user = super(UserForm, self).save(commit=False)
        if self.cleaned_data["password1"]:
            user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserLimitedForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ("email", "first_name", "last_name",
                  "groups", "docs_url", "bio")

    def __init__(self, *args, **kwargs):
        super(UserLimitedForm, self).__init__(*args, **kwargs)

        if not kwargs['instance'].is_in_group(GROUP_STUDENT):
            del self.fields['docs_url']
        if kwargs['instance'].is_in_group(GROUP_STUDENT):
            del self.fields['groups']


class MyLoginForm(auth_forms.AuthenticationForm):

    def __init__(self, request=None, *args, **kwargs):
        super(MyLoginForm, self).__init__(request=request, *args, **kwargs)
        self.fields['username'].widget.attrs.update({
            'class': 'form-control',
            'placeholder': 'username',
        })
        self.fields['password'].widget.attrs.update({
            'class': 'form-control',
            'placeholder': 'password',
        })


StudyFormset = inlineformset_factory(
    User, StudyExperience,
    extra=1,
    fields=('__all__'),
    can_delete=True,
)

WorkFormset = inlineformset_factory(
    User, WorkExperience,
    extra=1,
    fields=('__all__'),
    can_delete=True,
)

ResumeFormset = inlineformset_factory(
    User, Resume,
    extra=1,
    fields=('__all__'),
    can_delete=False,
)


class HorizontalFormHelper(FormHelper):

    def __init__(self, *args, **kwargs):
        super(HorizontalFormHelper, self).__init__(*args, **kwargs)
        self.form_tag = False
        self.label_class = 'col-lg-2'
        self.field_class = 'col-lg-6'
